import Flutter
import AppTrackingTransparency
import AdSupport

public class IosTrackingSagePermissionPlugin: NSObject, FlutterPlugin {
    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "ios_tracking_sage_permission", binaryMessenger: registrar.messenger())
        let instance = IosTrackingSagePermissionPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }
    
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "getTrackingSagePermission":
            if #available(iOS 14.0, *) {
                if let intValue = Int(exactly:ATTrackingManager.trackingAuthorizationStatus.rawValue) {
                    result(intValue)
                } else {
                    result(-1)
                }
            } else {
                result(3)
            }
        case "requestTrackingSagePermission":
            if #available(iOS 14.0, *) {
                ATTrackingManager.requestTrackingAuthorization { status in
                    if (status == .authorized) {
                        result(true)
                    } else {
                        result(false)
                    }
                }
            } else {
                result(true)
            }
            
        default:
            result(FlutterMethodNotImplemented)
        }
    }
}
